import { AssetManager, assetManager, AudioClip, Prefab } from "cc";

export class ResManager{


    private static _instance:ResManager = null!;

    static getInstance(){
        if(this._instance === null){
            this._instance = new ResManager();
        }


        return this._instance
    }


    private constructor(){

    }

    // loadPrefab(bundleName: string, prefabPath: string, cb: (prefab: Prefab | null) => void) {
    //     assetManager.loadBundle(bundleName, (e, bundle) => {
    //         bundle.load(prefabPath, Prefab, (err, prefab: Prefab) => {
    //             if (err) {
    //                 console.error(err);
    //                 cb(null);
    //                 return;
    //             }
    //             cb(prefab)
    //         })
    //     })
    // }

    loadPrefab(bundleName:string,prefabPath:string,cb:(prefab:Prefab|null) => void){
        assetManager.loadBundle(bundleName, (e, bundle) => {
            bundle.load(prefabPath,Prefab,(err,prefab:Prefab) => {
                if(err){
                    console.log(err);
                    cb(null);
                    return;
                }

                cb(prefab)
            })
        })
    }

    loadAudioClip(bundleName: string, audioPath: string, cb: (asset: AudioClip | null) => void) {
        assetManager.loadBundle(bundleName, (e, bundle) => {
            bundle.load(audioPath, AudioClip, (err, asset: AudioClip) => {
                if (err) {
                    console.error(err);
                    cb(null);
                    return;
                }
                cb(asset)
            })
        })
    }

    // loadBundle(bundleName: string, cb?: (bundle: AssetManager.Bundle | null) => void) {
    //     assetManager.loadBundle(bundleName, (e, bundle) => {
    //         cb && cb(bundle);
    //     });
    // }

    loadBundle(bundleName:string,cb?:(bundle:AssetManager.Bundle|null) => void){
        assetManager.loadBundle(bundleName,(e,bundle) =>{
            cb && cb(bundle)
        })
    }

    loadBundleAsync(bundleName:string):Promise<AssetManager.Bundle>{
        return new Promise<AssetManager.Bundle>(re => {
            this.loadBundle(bundleName,re);
        })
    }

    loadPrefabByBUrl(bUrl: IBundleUrl, cb: (prefab: Prefab | null) => void) {
        this.loadPrefab(bUrl.b, bUrl.l, cb); 
    }


    loadAudioByBUrl(bUrl: IBundleUrl, cb: (audioClip: AudioClip | null) => void) {
        this.loadAudioClip(bUrl.b, bUrl.l, cb); 
    }

    // loadAudioClip(bundleName:string,audioPath:string,cb:(asset:AudioClip|null) => void){
    //     assetManager.loadBundle(bundleName,(e,bundle)=>{
    //         bundle.load(audioPath,AudioClip,(err,asset:AudioClip) =>{
    //             if(err){
    //                 console.log(err)
    //                 return 
    //             }
    //             cb(asset)
    //         })
    //     })
    // }
}
